// @ts-nocheck
import {useState, useEffect, useRef} from 'react'

import {Modal, Form, Input, message} from 'antd'
import {createRole, modifyRole} from '@/services/role'


const Index = (props) => {
  const [form] = Form.useForm()
  const {visible, onClose, onOk, mode, data} = props
  useEffect(() => {
    if (visible && mode === 'modify') {
      form.setFieldsValue({name: data.name})
    }
  }, [visible])
  const handleOk = () => {
    form.validateFields().then(values => {
      if (mode === 'create') {
        createRole(values).then(res => {
          if (res.status === 200) {
            message.success(res.message).then()
            onOk()
          } else {
            message.error('新建失败！').then()
          }
        })

      } else {
        modifyRole({...values, role_id: data.role_id}).then(res => {
          if (res.status === 200) {
            message.success(res.message).then()
            onOk()
          } else {
            message.error('修改失败！').then()
          }
        })
      }
      form.resetFields()
    })
  }
  return (
    <Modal
      title={mode === 'create' ? '新建角色' : '修改角色'}
      maskClosable={false}
      destroyOnClose={true}
      width={'20vw'}
      visible={visible}
      onCancel={() => {
        form.resetFields();
        onClose();
      }}
      onOk={handleOk}
    >
      <Form
        form={form}
        labelCol={{span: 6}}
        wrapperCol={{span: 14}}
        autoComplete="off"
      >
        <Form.Item
          label="名称"
          name="name"
          rules={[{required: true, message: '请输入角色名称！'}]}
        >
          <Input/>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default Index;
